<template>
  <BaseDialog
    v-model="dialogVisible"
    :title="title"
    width="1100px"
    :before-close="handleClose"
  >
    <el-form
      ref="refDialogForm"
      v-loading="formLoading"
      class="set-dialog-form"
      :label-width="language === 'en' ? '180px' : '80px'"
      :model="formData"
      :rules="rules"
    >
      <el-row>
        <el-col :span="24">
          <el-form-item prop="base64Image">
            <template #label>
              <label>{{ $t('recipe.recipeImage') }}</label>
            </template>
            <UploadImage
              v-model:file-list="fileList"
              list-type="picture-card"
              :auto-upload="false"
              :on-change="handleChange"
              @on-exceed="handleExceed"
              @on-remove="handleRemove"
            >
              <template #trigger>
                <el-icon><i-ep-Plus /></el-icon>
              </template>
            </UploadImage>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="$t('recipe.recipeName')" prop="name">
            <TextInput
              v-model="formData.name"
              :label="$t('recipe.recipeName')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="菜系" prop="cookStyle" label-width="110px">
            <BaseSelect
              v-model="formData.cookStyle"
              :options="recipeCookStyleOptions"
              label="菜系"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="口味" prop="tasteStyle">
            <BaseSelect
              v-model="formData.tasteStyle"
              :options="recipeTasteOptions"
              label="口味"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('recipe.applicDeviceModel')"
            prop="model"
            label-width="110px"
          >
            <BaseSelect
              v-model="formData.model"
              :options="deviceModelList"
              :label="$t('recipe.applicDeviceModel')"
              multiple
              filterable
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="3"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="适用国家" prop="country">
            <BaseSelect
              v-model="formData.country"
              :options="countryList"
              label="适用国家"
              multiple
              filterable
              collapse-tags
              collapse-tags-tooltip
              :max-collapse-tags="3"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('recipe.recipeType')"
            prop="type"
            label-width="110px"
          >
            <BaseSelect
              v-model="formData.type"
              :options="g_options.recipeTypeOptions"
              :label="$t('recipe.recipeType')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item
            :label="$t('recipe.portion')"
            prop="cookWeight"
            label-width="80px"
          >
            <!-- <TextInput
              v-model="formData.cookWeight"
              :label="$t('recipe.portion')"
              verify-type="nzint"
              maxlength="10"
            /> -->
            <BaseSelect
              v-model="formData.cookWeight"
              :options="recipeWeightOptions"
              :label="$t('recipe.portion')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="说明" prop="description" label-width="110px">
            <TextInput v-model="formData.description" label="说明" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label="简介" prop="introduction">
            <TextInput
              v-model="formData.introduction"
              type="textarea"
              :rows="2"
              maxlength="256"
              label="简介"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item style="margin-bottom: 0" required>
            <template #label>
              <label>{{ $t('recipe.addStep') }}</label>
            </template>
            <el-button
              type="primary"
              style="margin-bottom: 10px"
              @click="handleAddStep"
              >{{ $t('public.add') }}</el-button
            >
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item label-width="0" class="form-item-table" prop="stepList">
            <BaseTable
              ref="refContentTable"
              v-loading="tableLoading"
              :data="formData.stepList"
              row-key="id"
            >
              <TableColumn
                prop="num"
                label="步骤序号"
                :column-width="columnWidthObj.num"
              >
                <template #default="{ $index }">
                  <span>{{ $index + 1 }}</span>
                </template>
              </TableColumn>
              <TableColumn
                prop="timeOffset"
                label="步骤时长(秒)"
                :column-width="columnWidthObj.timeOffset"
              />
              <TableColumn
                prop="name"
                label="步骤内容"
                :column-width="columnWidthObj.name"
              />
              <TableColumn
                prop="action"
                fixed="right"
                :label="$t('public.action')"
                :column-width="columnWidthObj.action"
              >
                <template #default="{ row, $index }">
                  <el-button
                    text
                    :disabled="$index === 0"
                    @click="handleStepMoveUp(row, $index)"
                  >
                    {{ $t('recipe.moveUp') }}
                  </el-button>
                  <el-button
                    text
                    :disabled="$index === formData.stepList.length - 1"
                    @click="handleStepMoveDown(row, $index)"
                  >
                    {{ $t('recipe.moveDown') }}
                  </el-button>
                  <el-button text @click="handleStepEdit(row, $index)">
                    {{ $t('public.edit') }}
                  </el-button>
                  <el-button text @click="handleStepDelete(row, $index)">{{
                    $t('public.delete')
                  }}</el-button>
                </template>
              </TableColumn>
            </BaseTable>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="form-dialog-footer">
        <el-button plain @click="handleClose">{{
          $t('public.cancel')
        }}</el-button>
        <el-button type="primary" @click="handleSubmitForm">{{
          $t('public.confirm')
        }}</el-button>
      </div>
    </template>
  </BaseDialog>

  <AddStep
    v-if="addStepVisible"
    v-model="addStepVisible"
    :type="addOrEditType"
    :row="stepRow"
    :stepList="formData.stepList"
    :ingredientIndex="ingredientIndex"
    @add="handleAddStepCb"
    @update="handleUpdateStepCb"
  />
</template>

<script setup>
import AddStep from './AddStep.vue'

const props = defineProps({
  type: {
    type: String,
    default: 'add' // add | edit
  },
  id: {
    type: String,
    default: ''
  },
  tenantId: {
    type: String,
    default: ''
  }
})

const emit = defineEmits(['update'])
const dialogVisible = defineModel({
  type: Boolean,
  default: false
})
const { language } = storeToRefs(useAppStore())
const title = computed(() => (props.type === 'add' ? '新建菜谱' : '编辑菜谱'))

const refDialogForm = ref(null)
const formLoading = ref(false)
const formData = ref({
  base64Image: '',
  name: '',
  cookStyle: '',
  tasteStyle: '',
  model: '',
  country: '',
  type: '',
  cookWeight: '',
  description: '',
  introduction: '',
  stepList: []
})
const rules = {
  base64Image: g_rules.uploadFileRule(g_t('recipe.recipeImage')),
  name: g_rules.commonInputText(g_t('recipe.recipeName')),
  cookStyle: g_rules.selectRule('菜系'),
  tasteStyle: g_rules.selectRule('口味'),
  model: g_rules.commonInputText(g_t('recipe.applicDeviceModel')),
  country: g_rules.selectRule('适用国家'),
  type: g_rules.selectRule(g_t('recipe.recipeType')),
  cookWeight: g_rules.commonInputText(g_t('recipe.portion')),
  stepList: {
    required: true,
    message: '请添加步骤',
    trigger: ['blur', 'change']
  }
}
const fileList = ref([])
const recipeCookStyleOptions = ref([])
const recipeTasteOptions = ref([])
const deviceModelList = ref([])
const countryList = ref([])
const recipeWeightOptions = ref([])
const refContentTable = ref(null)
const tableLoading = ref(false)
const columnWidthObj = ref({})
// 弹框参数
const addStepVisible = ref(false)
const stepRow = ref({})
const addOrEditType = ref('')
const stepTableIndex = ref('')
const ingredientIndex = ref(1)

watch(
  () => formData.value.base64Image,
  nv => {
    nextTick(() => {
      refDialogForm.value.validateField(['base64Image'])
    })
  }
)

watch(
  () => formData.value.stepList,
  (nv, ov) => {
    useTableColumnWidth({
      refTable: refContentTable.value
    }).getTableColumnWidth(data => {
      columnWidthObj.value = data
    })
    nextTick(() => {
      refDialogForm.value.validateField(['stepList'])
    })
  },
  {
    deep: true
  }
)

onMounted(() => {
  props.type === 'edit' && getFormData()
  getQueryModelList()
  getDictDropList()
})

const getFormData = _ => {
  formLoading.value = true
  g_api.recipe
    .apiRecipeQueryDetail({ id: props.id })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        formData.value = {
          ...formData.value,
          id: '',
          picturePath: ''
        }
        g_utils.assignFormData(formData.value, data)
        if (data.picturePath) {
          fileList.value = [
            {
              name: data.picturePath,
              url: g_utils.showImg(data.picturePath)
            }
          ]
          formData.value.base64Image = data.picturePath
        }
        formData.value.model = data.model.split(',')
        formData.value.country = data.country.split(',')
        console.log('formData.value', formData.value)
      }
    })
    .finally(() => {
      formLoading.value = false
    })
}

const getQueryModelList = _ => {
  g_api.device
    .apiDeviceQueryModelList()
    .then(({ code, data }) => {
      if (code === '200' && data) {
        // console.log('data', data)
        deviceModelList.value = data.map(item => ({
          value: item,
          label: item
        }))
      }
    })
    .finally(() => {})
}

const getDictDropList = _ => {
  g_api.recipe
    .apiDictDropList({
      dictType: 'cook_style'
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        recipeCookStyleOptions.value = data
      }
    })
  g_api.recipe
    .apiDictDropList({
      dictType: 'taste_style'
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        recipeTasteOptions.value = data
      }
    })
  g_api.recipe
    .apiDictDropList({
      dictType: 'country'
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        countryList.value = data
      }
    })
  g_api.recipe
    .apiDictDropList({
      dictType: 'cook_weight'
    })
    .then(({ code, data }) => {
      if (code === '200' && data) {
        recipeWeightOptions.value = data
      }
    })
}

const handleClose = _ => {
  dialogVisible.value = false
}

const handleChange = (file, files) => {
  console.log('handleChange', file, files)
  g_utils.fileToBase64(file.raw).then(res => {
    formData.value.base64Image = res
    formData.value.picturePath = ''
  })
}

const handleExceed = (files, uploadFiles) => {
  console.log('handleExceed', files, uploadFiles)
  g_utils.fileToBase64(files[0]).then(res => {
    formData.value.base64Image = res
    formData.value.picturePath = ''
  })
}

const handleRemove = file => {
  console.log('handleRemove', file)
  formData.value.base64Image = ''
  formData.value.picturePath = ''
}

const handleAddStep = _ => {
  addStepVisible.value = true
  stepRow.value = {}
  addOrEditType.value = 'add'
  ingredientIndex.value =
    formData.value.stepList.filter(item => item.ingredientType === 'material')
      .length + 1
}

const handleStepMoveUp = (row, i) => {
  const { stepList } = formData.value
  ;[stepList[i - 1], stepList[i]] = [stepList[i], stepList[i - 1]]
}

const handleStepMoveDown = (row, i) => {
  const { stepList } = formData.value
  ;[stepList[i + 1], stepList[i]] = [stepList[i], stepList[i + 1]]
}

const handleStepEdit = (row, i) => {
  addStepVisible.value = true
  stepRow.value = row
  addOrEditType.value = 'edit'
  stepTableIndex.value = i
  ingredientIndex.value =
    formData.value.stepList
      .slice(0, i)
      .filter(item => item.ingredientType === 'material').length + 1
}

const handleStepDelete = (row, i) => {
  ElMessageBox.confirm(
    `是否删除该菜谱步骤【${row.name}】?`,
    g_t('public.tip'),
    {
      confirmButtonText: g_t('public.confirm'),
      cancelButtonText: g_t('public.cancel'),
      type: 'warning'
    }
  )
    .then(() => {
      formData.value.stepList.splice(i, 1)
    })
    .catch(() => {})
}

const handleAddStepCb = data => {
  console.log('handleAddStepCb', data)
  // const num = formData.value.stepList.length + 1
  // if (data.ingredientType === 'material') {
  //   data.ingredientList.forEach(item => {
  //     formData.value.stepList.push({
  //       ...data,
  //       ...item,
  //       num
  //     })
  //   })
  // } else {
  //   formData.value.stepList.push({
  //     ...data,
  //     num,
  //     processId: ''
  //   })
  // }
  formData.value.stepList.push(data)
}

const handleUpdateStepCb = data => {
  console.log('handleUpdateStepCb', data)
  // let list = [data]
  // if (data.ingredientType === 'material') {
  //   list = data.ingredientList.map(item => {
  //     return {
  //       ...data,
  //       ...item,
  //       num: stepTableIndex.value + 1
  //     }
  //   })
  // }
  // formData.value.stepList.splice(stepTableIndex.value, 1, ...list)
  formData.value.stepList.splice(stepTableIndex.value, 1, data)
}

const handleSubmitForm = () => {
  if (formLoading.value) return
  refDialogForm.value.validate(valid => {
    console.log('formData.value', formData.value)
    if (!valid) return
    formLoading.value = true
    const urlMethod =
      props.type === 'add'
        ? g_api.recipe.apiRecipeCreate
        : g_api.recipe.apiRecipeUpdate
    urlMethod({
      ...formData.value,
      base64Image: g_utils.isExternal(formData.value.base64Image)
        ? ''
        : formData.value.base64Image.replace(/^data:image\/[a-z]+;base64,/, ''),
      model: formData.value.model.join(','),
      country: formData.value.country.join(',')
    })
      .then(res => {
        if (res.code === '200') {
          ElMessage({
            message: res.message,
            type: 'success'
          })
          handleClose()
          emit('update')
        }
      })
      .finally(() => {
        formLoading.value = false
      })
  })
}
</script>

<style scoped lang="scss">
:deep(.el-upload-list) {
  margin-top: 0;
  .el-upload-list__item {
    line-height: 24px;
    margin-bottom: 0;
    .el-icon--close-tip {
      color: var(--main-theme);
    }
  }
  .el-upload-list__item.is-success .el-upload-list__item-name:hover {
    color: var(--main-theme);
  }
}
</style>
